package com.hk.admin.module.system.service;

import com.hk.admin.common.constant.GlobalEnum;
import com.hk.admin.common.base.dto.message.Message;
import com.hk.admin.common.base.dto.page.Pagination;
import com.hk.admin.common.dto.system.user.UserDTO;
import com.hk.admin.common.dto.system.user.UserSearchDTO;
import com.hk.admin.common.model.system.MenuModel;
import com.hk.admin.common.model.system.RoleModel;
import com.hk.admin.common.model.system.UserModel;
import com.hk.admin.common.base.service.BaseService;
import com.hk.admin.common.util.FileUtil;
import com.hk.admin.module.system.dao.RoleRepository;
import com.hk.admin.spring.config.FileUploadConfig;
import com.hk.admin.module.system.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService extends BaseService {

    @Autowired
    FileUploadConfig fileUploadConfig;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    /**
     * 查询所有
     */
    public ResponseEntity<Message> list(UserSearchDTO dto) {
        // 分页查询
        Page<UserModel> pageList = userRepository.findAll(UserModel.createSpecification(dto), getPageable(dto));
        // 处理数据返回到前端
        Pagination pagination = transformModelIntoDTO(pageList);
        return success(pagination);
    }

    /**
     * 处理返回前端数据
     */
    private Pagination transformModelIntoDTO(Page<UserModel> pageList) {
        Pagination pagination = new Pagination(pageList);
        List<UserModel> list = pageList.getContent();
        List<UserDTO> dtoList = new ArrayList<>();
        list.forEach(model -> {
            UserDTO dto = new UserDTO(model);
            dto.fitRoles(model);
            dtoList.add(dto);
        });
        pagination.setContent(dtoList);
        return pagination;
    }

    /**
     * 查询一个
     */
    public ResponseEntity<Message> query(Long id) {
        UserModel model = userRepository.findOne(id);
        if (model == null) {
            return idError();
        }
        UserDTO dto = new UserDTO(model);
        dto.fitRoles(model);
        return success(dto);
    }

    /**
     * 保存
     */
    public ResponseEntity<Message> save(UserDTO dto) {
        // 判断手机号码是否有重复
        if (checkPhoneNumber(dto)) {
            return error("手机号码重复");
        }
        // 判断是否有图片
        if (checkHasImage(dto)) {
            String rootPath = fileUploadConfig.getRootPath();
            String imageUrlPrefix = fileUploadConfig.getImageUrlPrefix();
            String imageUrl = FileUtil.writeImageBase64ToFile(dto.getHeadPictureBase64(), rootPath, imageUrlPrefix);
            dto.setHeadPictureUrl(imageUrl);
        }
        addOrUpdate(dto);
        return saveSuccess();
    }

    /**
     * 判断手机号码是否有重复
     */
    private boolean checkPhoneNumber(UserDTO dto) {
        boolean repeated = false;
        UserModel userModel = userRepository.findByPhoneNumberAndDeleted(dto.getPhoneNumber(), GlobalEnum.DELETED.NO.getKey());
        // 添加时重复
        if (dto.getId() == null && userModel != null) {
            repeated = true;
        }
        // 更新时重复
        if (dto.getId() != null && userModel != null && !userModel.getId().equals(dto.getId())) {
            repeated = true;
        }
        return repeated;
    }

    /**
     * 判断是否有图片
     */
    private boolean checkHasImage(UserDTO dto) {
        return dto.getHeadPictureBase64() != null && dto.getHeadPictureBase64().startsWith(FileUtil.BASE64_START_FLAG);
    }

    /**
     * 添加或者更新
     */
    private boolean addOrUpdate(UserDTO dto) {
        UserModel model = null;
        if (dto.getId() != null) {
            model = userRepository.findOne(dto.getId());
        }
        if (model == null) {
            model = new UserModel(dto);
        } else {
            model.update(dto);
        }
        // 更新人员和角色的关系
        List<RoleModel> roles = roleRepository.findByIdIn(dto.getRoleIds());
        model.setRoles(roles);
        userRepository.save(model);
        return true;
    }

    /**
     * 删除
     */
    public ResponseEntity<Message> delete(Long id) {
        UserModel model = userRepository.findOne(id);
        if (model == null) {
            return idError();
        }
        model.delete();
        userRepository.save(model);
        return saveSuccess();
    }


    /**
     * 检查手机号码是否存在
     */
    public ResponseEntity<Message> checkNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return success(null);
        }
        UserModel model = userRepository.findByPhoneNumberAndDeleted(phoneNumber, GlobalEnum.DELETED.NO.getKey());
        if (model != null) {
            return error("手机号码重复");
        }
        return success(null);
    }
}
